package com.xidata.dict.client.embedded;

import com.xidata.dict.model.Language;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TargetLanguageFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String header = httpServletRequest.getHeader(Constants.TARGET_LANGUAGE_HEADER);
        if (!StringUtils.isEmpty(header)) {
            Language byCode = Language.getByCode(header);
            if (byCode != null) TargetLanguageHolder.set(byCode.name());
            else TargetLanguageHolder.set(header);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
